package com.katze.boot.plugins.feign;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.function.BiFunction;
import java.util.function.Function;

public abstract class FeignRequester<T> {

    @Autowired
    private T service;

    protected String name;

    public FeignRequester() {
        Type type = getClass().getGenericSuperclass();
        Class<?> c = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
        this.name = c.getAnnotation(FeignClient.class).name();
    }

    public <R>R execute(String groupId, Function<URI, R> action) {
        URI uri = RouteTargeter.get(groupId).resolve(name);
        return action.apply(uri);
    }

    public <R>R execute(String groupId, BiFunction<URI, T, R> action) {
        URI uri = RouteTargeter.get(groupId).resolve(name);
        return action.apply(uri, service);
    }

    public <R>R execute(String groupId, String serviceId, BiFunction<URI, T, R> action) {
        URI uri = RouteTargeter.get(groupId, serviceId).resolve(name);
        return action.apply(uri, service);
    }
}
